package com.zp.datax.service.impl;

import com.zp.datax.core.model.DataxJobLog;
import com.zp.datax.core.result.ReturnT;
import com.zp.datax.dao.DataxJobLogDao;
import com.zp.datax.service.DataxJobLogService;
import lombok.Cleanup;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Service
public class DataxJobLogServiceImpl implements DataxJobLogService {

    @Resource
    private DataxJobLogDao dataxJobLogDao;
    private final static long CONTENT_LIMIT = 2000L;

    /**
     * 分页查询
     *
     * @param start
     * @param length
     * @param taskId
     * @return
     */
    @Override
    public Map<String, Object> pageList(int start, int length, int taskId, int status, String startTime, String endTime) {


        List<DataxJobLog> pageList = dataxJobLogDao.pageList(start, length, taskId, status, startTime, endTime);
        int pageListCount = dataxJobLogDao.pageListCount(taskId, status, startTime, endTime);

        // package result
        Map<String, Object> maps = new HashMap<String, Object>();
        maps.put("recordsTotal", pageListCount);        // 总记录数
        maps.put("recordsFiltered", pageListCount);    // 过滤后的总记录数
        maps.put("data", pageList);                    // 分页列表
        return maps;
    }

    /**
     * 加载日志
     *
     * @param sysId
     * @return
     */
    @SneakyThrows
    @Override
    public ReturnT<String> logDetailPage(int sysId) {

        DataxJobLog dataxJobLog = dataxJobLogDao.load(sysId);

        if (Objects.isNull(dataxJobLog)) return new ReturnT<>(ReturnT.FAIL_CODE, "日志不存在");

        if (Objects.isNull(dataxJobLog.getPath())) {
            ReturnT<String> fail = ReturnT.SUCCESS;
            fail.setData(Objects.nonNull(dataxJobLog.getMsg())
                    ? String.format("本次调用可能失败，日志文件尚未生成 :: %s", dataxJobLog.getMsg())
                    : "本次调用可能失败，日志文件尚未生成，建议人工查看系统日志");
            return fail;
        }

        File file = new File(dataxJobLog.getPath());

        if (!file.isFile()) {
            ReturnT<String> successEmpty = ReturnT.SUCCESS;
            successEmpty.setData(String.format("taskId :: %d，%s非日志文件", dataxJobLog.getTaskId(), file.getPath()));
            return successEmpty;
        }

        long length = file.length();

        @Cleanup
        Reader reader = new FileReader(file);
        @Cleanup
        BufferedReader bufferedReader = new BufferedReader(reader);
        @Cleanup
        LineNumberReader lineNumberReader = new LineNumberReader(bufferedReader);

        long end = length - CONTENT_LIMIT;
        if (end > 0L) {
            lineNumberReader.skip(end);
        }

        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = lineNumberReader.readLine()) != null) {
            sb.append(line).append("\n");
        }

        ReturnT<String> success = ReturnT.SUCCESS;
        success.setData(sb.toString());
        return success;
    }

    @Override
    public void update(DataxJobLog dataxJobLog) {
        dataxJobLogDao.update(dataxJobLog);
    }

    @Override
    public void add(DataxJobLog dataxJobLog) {
        dataxJobLogDao.save(dataxJobLog);
    }

    @Override
    public void removeByCreateTime(String createTime) {
        dataxJobLogDao.removeByCreateTime(createTime);
    }

    @Override
    public String searchMin() {
        return dataxJobLogDao.findMin();
    }

    @Override
    public DataxJobLog searchBySysId(Integer sysId) {
        return dataxJobLogDao.load(sysId);
    }

}
